package com.mach.platform.api.repository;

import com.mach.platform.api.domain.Team;
import com.mach.platform.repository.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface TeamRepo extends BaseRepository<Team> {

    /**
     * 根据openId获取对应的所有站房id
     * @param openId
     * @return
     */
    List<Team> findByOpenId(String openId);

    /**
     * 根据领队id和成员数组id删除数据
     * @param stationId
     * @param memberId
     * @return
     */
    @Modifying
    @Query(value = "delete from team where station_id = ?1 and open_id in (?2)", nativeQuery = true)
    int deleteTeamMember(Long stationId, String[] memberId);

    /**
     * 更新成员为团队成员
     * @param stationId 团队站房id
     * @param openId 成员openId
     * @return
     */
    @Modifying
    @Query(value = "update team set is_leader = 0 where station_id = ?1 and open_id = ?2", nativeQuery = true)
    int updateMember(Long stationId, String openId);

    /**
     * 更新成员为团队领队
     * @param stationId 团队站房id
     * @param openId 新领队openId
     * @return
     */
    @Modifying
    @Query(value = "update team set is_leader = 1 where station_id = ?1 and open_id = ?2", nativeQuery = true)
    int updateLeader(Long stationId, String openId);

    /**
     * 通过openId和stationId查询团队信息
     * @return
     */
    Team findByOpenIdAndStationId(String openId, Long stationId);

    /**
     * @param openId
     * @return 获取团队列表
     */
    @Query(value = "select station_id stationId, team_name teamName from team where open_id = ?1", nativeQuery = true)
    List<Map> findTeamListByOpenId(String openId);

    /**
     * 获取用户所有站房下有关的成员的信息
     * @param openId
     * @return
     */
    @Query(value = "select distinct open_id, nick_name from team where station_id in (select distinct station_id from team where open_id = ?1) and open_id != ?1", nativeQuery = true)
    List<Map> findAllTeamMember(String openId);

    /**
     * 通过openId和站房id查询团队信息
     * @param openId
     * @param stationId
     * @return
     */
    @Query(value = "select * from team where is_leader = 1 and open_id = ?1 and station_id = ?2", nativeQuery = true)
    Team checkIsLeader(String openId, Long stationId);
}
